import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const { token } = store.getters
    if (token) {
      config.headers.Authorization = token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
service.interceptors.response.use((response) => {
  // console.log(response.data)
  const { token, msg, success } = response.data
  if (success) {
    // 返回token(这里的token用的是data储存)
    return token
  } else {
    Message.error(msg)
    // 返回一个错误的promise实例
    return Promise.reject(new Error(msg))
  }
}, (error) => {
  return Promise.reject(error)
})
export default service
